<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\db\exception\PDOException;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 罐箱分配结果
 *
 */
class XPotfp extends Backend
{
    /**
     * XPotfp模型对象
     * @var \app\admin\model\XPotfp
     */
    protected $model = null;
    protected $sq=null;
    protected $quickSearchField = ['ID'];

    protected $defaultSortField = 'ID,desc';
    protected $noNeedLogin      = ['*'];
    protected $preExcludeFields = [''];

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\admin\model\XPotfp;
        $this->sq =new \app\admin\model\XPotsq();
    }
    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $wheres='';
        foreach ($where as $k=>$item) {
                $wheres[]=['x_potsq.'.substr( $item[0],strripos( $item[0],".")+1),$item[1],$item[2]];

        }
        $res = $this->sq
            ->field('x_potsq.*,DEPARTMENT.DEPTNAME,codelib.codename')
            ->join('DEPARTMENT',"x_potsq.DEPT=DEPARTMENT.DEPTID")
            ->join('codelib','x_potsq.CONTYPE=codelib.code')
            ->with('fp')
            ->alias($alias)
            ->where('codelib.CODETYPE','potkind')
            ->where($wheres)
            ->where('TJFLAG','1')
//            ->fetchSql()->select();
            ->paginate($limit);
//var_dump($res);die;
        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * 罐箱分配
     *
     */
    public function distribution(){
        $id=$this->request->get('TKID');
        $da=$this->sq->where('TKID',$id)->find();
        $sql="SELECT  case when dbo.f_getpotfp_status(tcno)=0 then '未分配' else '已分配' end as status,tcno,OWER,CODENAME ,TANKCODE,
(select TOP 1 HCDATE from CONLOADPLAN WHERE CNTRNO=X_POT.TCNO and HCDATE IS NOT NULL ORDER BY HCDATE DESC) as HCDATE ,
(SELECT TOP 1 HCPLACE FROM CONLOADPLAN WHERE CNTRNO=X_POT.TCNO and HCDATE IS NOT NULL ORDER BY HCDATE DESC) as HCPLACE, 
(select MIN(FREESTORAGEFROM) from CONLOADPLAN WHERE CNTRNO=X_POT.TCNO AND HCDATE IS NULL) as FREESTORAGEFROM
FROM X_POT join codelib on  X_POT.KIND=codelib.CODE where X_POT.status='SYZ' and  X_POT.KIND='$da[CONTYPE] ' and codelib.codetype='potkind'
ORDER BY dbo.f_getpotfp_status(X_POT.tcno)";
        $list=Db::query($sql);
        $this->success('',[$da,$list]);
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            $adminInfo          = $this->auth->getInfo();
            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }
            $add=[];
            foreach ($data['TCNO'] as $datum) {
                $add[]=[
                  'TKID'=>$data['TKID'],
                    'TCNO'=>$datum,
                    'STARTDATE'=>$data['STARTDATE'],
                    'YJENDDATE'=>$data['YJENDDATE'],
                    'OP'=>$adminInfo['nickname'],
                    'OPTIME'=>date('Y-m-d H:i:s',time()),
                ];
            }
            $result = false;
            Db::startTrans();
            try {
                $this->model->where('TKID',$data['TKID'])->delete();
                $result = $this->model->saveAll($add);
                Db::commit();
            } catch (ValidateException|PDOException|Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    /**
     * 锁定
     */
    public function lock(){
       $get= $this->request->get();
        $sa=$this->model->where('id',$get['id'])->save(['LOCKED'=>'1','ENDDATE'=>$get['ENDDATE'],'LOCKDATE'=>date('Y-m-d H:i:s',time())]);
        if($sa){
            $this->success('成功');
        }else{
            $this->error('失败');
        }
    }
    /**
     * 解除锁定
     */
    public function nolock(){
        $get= $this->request->get();
        $sa=$this->model->where('id',$get['id'])->save(['LOCKED'=>'0','ENDDATE'=>null,'LOCKDATE'=>null]);

            $this->success('成功');

    }
    /**
     * 退回
     */
    public function retreat(){
        $get= $this->request->get('TKID');
       $sa= $this->sq->where('TKID',$get)->save(['TJFLAG'=>0]);
        if($sa){
            $this->success('退回成功');
        }else{
            $this->error('失败');
        }
    }
    /**
     * 删除
     * @param array $ids
     */
    public function del(array $ids = [])
    {


        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $this->model->where($this->dataLimitField, 'in', $dataLimitAdminIds);
        }

        $pk    = $this->model->getPk();
        $id  = $this->request->get('id');
        $data  = $this->model->where($pk, 'in', $id)->select();
        $count = 0;
        Db::startTrans();
        try {
            foreach ($data as $v) {
                $count += $v->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success(__('Deleted successfully'));
        } else {
            $this->error(__('No rows were deleted'));
        }
    }
}